<template>
  <div class="home-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2 class="page-title">
          {{ pageTitle }}
        </h2>
        <span class="note-count">共 {{ noteStore.total }} 篇笔记</span>
      </div>
      
      <div class="toolbar-right">
        <el-select
          v-model="filterNotebook"
          placeholder="筛选笔记本"
          clearable
          style="width: 150px; margin-right: 12px;"
          @change="handleFilter"
        >
          <el-option
            v-for="notebook in notebookStore.notebooks"
            :key="notebook.id"
            :label="notebook.name"
            :value="notebook.id"
          />
        </el-select>
        
        <el-select
          v-model="filterTag"
          placeholder="筛选标签"
          clearable
          style="width: 150px;"
          @change="handleFilter"
        >
          <el-option
            v-for="tag in tagStore.tags"
            :key="tag.id"
            :label="tag.name"
            :value="tag.id"
          />
        </el-select>
      </div>
    </div>
    
    <!-- 笔记列表 -->
    <div v-loading="noteStore.loading" class="notes-grid">
      <div
        v-for="note in displayNotes"
        :key="note.id"
        class="note-card"
        @click="openNote(note.id)"
      >
        <div class="note-header">
          <h3 class="note-title">
            <el-icon v-if="note.is_pinned" class="pin-icon"><Star /></el-icon>
            {{ note.title }}
          </h3>
          <el-dropdown @command="handleNoteCommand($event, note.id)">
            <el-icon class="note-menu"><MoreFilled /></el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        
        <div class="note-content">
          {{ stripHtml(note.content) }}
        </div>
        
        <div class="note-footer">
          <div class="note-tags">
            <el-tag
              v-for="tag in note.tags"
              :key="tag.id"
              size="small"
              :color="tag.color"
              style="margin-right: 4px;"
            >
              {{ tag.name }}
            </el-tag>
          </div>
          <div class="note-time">
            {{ relativeTimeFormat(note.updated_at) }}
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <el-empty v-if="!noteStore.loading && displayNotes.length === 0" description="暂无笔记" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { useNoteStore } from '@/stores/note'
import { useNotebookStore } from '@/stores/notebook'
import { useTagStore } from '@/stores/tag'
import { useUserStore } from '@/stores/user'
import { stripHtml, relativeTimeFormat } from '@/utils'

const router = useRouter()
const noteStore = useNoteStore()
const notebookStore = useNotebookStore()
const tagStore = useTagStore()
const userStore = useUserStore()

const filterNotebook = ref(null)
const filterTag = ref(null)

const displayNotes = computed(() => {
  return noteStore.searchResults.length > 0 ? noteStore.searchResults : noteStore.notes
})

const pageTitle = computed(() => {
  return noteStore.searchResults.length > 0 ? '搜索结果' : '所有笔记'
})

const isLoading = ref(false)

onMounted(async () => {
  console.log('[首页] onMounted 开始')
  console.log('[首页] isAuthenticated:', userStore.isAuthenticated)
  console.log('[首页] localStorage token:', localStorage.getItem('access_token')?.substring(0, 20) + '...')
  
  // 等待一个 tick 确保 DOM 和状态都已准备好
  await new Promise(resolve => setTimeout(resolve, 100))
  
  console.log('[首页] 延迟后 isAuthenticated:', userStore.isAuthenticated)
  console.log('[首页] 延迟后 localStorage token:', localStorage.getItem('access_token')?.substring(0, 20) + '...')
  
  // 只有在已登录时才加载数据
  if (userStore.isAuthenticated) {
    console.log('[首页] 开始加载数据')
    loadData()
  } else {
    console.log('[首页] 未登录，跳过数据加载')
  }
})

async function loadData() {
  if (isLoading.value) {
    console.log('[首页] 数据正在加载中，跳过')
    return
  }
  
  console.log('[首页] loadData 开始执行')
  isLoading.value = true
  try {
    console.log('[首页] 发起并行请求: notes, notebooks, tags')
    await Promise.all([
      noteStore.fetchNotes(),
      notebookStore.fetchNotebooks(),
      tagStore.fetchTags()
    ])
    console.log('[首页] 所有数据加载完成')
  } catch (error) {
    console.error('[首页] 加载数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

function handleFilter() {
  const params = {}
  if (filterNotebook.value) params.notebook_id = filterNotebook.value
  if (filterTag.value) params.tag_id = filterTag.value
  noteStore.fetchNotes(params)
}

function openNote(id) {
  router.push(`/editor/${id}`)
}

async function handleNoteCommand(command, noteId) {
  if (command === 'edit') {
    openNote(noteId)
  } else if (command === 'delete') {
    await ElMessageBox.confirm('确定要删除这篇笔记吗？', '提示', {
      type: 'warning'
    })
    await noteStore.removeNote(noteId)
  }
}
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.note-count {
  color: #909399;
  font-size: 14px;
}

.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  min-height: 400px;
}

.note-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.note-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.note-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  align-items: center;
  gap: 4px;
}

.pin-icon {
  color: #f56c6c;
}

.note-menu {
  color: #909399;
  cursor: pointer;
  font-size: 18px;
}

.note-menu:hover {
  color: #409eff;
}

.note-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.note-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.note-tags {
  flex: 1;
  overflow: hidden;
}

.note-time {
  color: #909399;
  font-size: 12px;
  white-space: nowrap;
  margin-left: 12px;
}
</style>

